package chatdialogservicelogic

import (
	"context"

	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *pb.ChatDialogUpdateReq) (*pb.ChatDialogUpdateResp, error) {
	dialog, err := l.svcCtx.ChatDialogModel.RenameAndReturn(l.ctx, in.Dialog.Id, in.Dialog.UserId, in.Dialog.Name)
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialog Rename: failed, by Dialog Id: %s, User Id: %d, new Name: %s",
			in.Dialog.Id, in.Dialog.UserId, in.Dialog.Name)
	}

	return &pb.ChatDialogUpdateResp{
		Dialog: &pb.ChatDialog{
			Id:           dialog.ID.Hex(),
			UpdateAt:     dialog.UpdateAt.Unix(),
			CreateAt:     dialog.CreateAt.Unix(),
			Name:         dialog.Name,
			LastActiveAt: dialog.LastActiveAt.Unix(),
			AssistantId:  dialog.AssistantId.Hex(),
			UserId:       dialog.UserId,
		},
	}, nil
}
